<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 基础表格 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.keyword" placeholder="请输入部门名或相关描述" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
            </div>
            <el-table :data="tableData" border class="table" header-cell-class-name="table-header">
                <el-table-column prop="departId" label="ID" align="left" show-overflow-tooltip></el-table-column>
                <el-table-column prop="departName" label="部门名"></el-table-column>
                <el-table-column prop="desc" label="描述"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page.sync="pageParams.currentPage"
                    :page-size.sync="pageParams.pageSize"
                    :page-count="pageParams.totalElements"
                    :total="pageParams.totalElements"
                    @current-change="getDeaprtData"
                ></el-pagination>
            </div>
        </div>

        <el-dialog title="添加" :visible.sync="addVisible" width="30%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item prop="departName" label="部门名">
                    <el-input v-model="form.departName"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input type="textarea" rows="4" v-model="form.desc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="部门名">
                    <el-input disabled v-model="form.departName"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input type="textarea" rows="4" v-model="form.desc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
//import { fetchData } from '../../api/index';
import * as api from '@/api/index';
export default {
    name: 'depart',
    data() {
        return {
            query: {
                keyword: ''
            },
            rules: {
                departName: [{ required: true, message: '请输入部门名', trigger: 'blur' }]
            },
            pageParams: {
                currentPage: 1,
                pageSize: 10,
                totalElements: 20,
                totalPages: 1
            },
            loginUser: {
                userId: '',
                username: '',
                usertype: 0
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            pageTotal: 4,
            form: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            this.getDeaprtData();
            this.loginUser.userId = localStorage.getItem('userId');
            this.loginUser.username = localStorage.getItem('username');
            this.loginUser.usertype = localStorage.getItem('usertype');
        },
        getDeaprtData() {
            let currentPage = this.pageParams.currentPage;
            let pageSize = this.pageParams.pageSize;
            let params = {
                keyword: this.query.keyword
            };
            api.searchDepartPage(currentPage, pageSize, params)
                .then((res) => {
                    if (res.code === 200) {
                        this.tableData = res.data.content;
                        this.pageParams.currentPage = res.data.currentPage;
                        this.pageParams.pageSize = res.data.pageSize;
                        this.pageParams.totalElements = res.data.totalElements;
                        this.pageParams.totalPages = res.data.totalPages;
                    }
                })
                .then((err) => {
                    console.log(err);
                });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    api.deleteDepartById(row.departId)
                        .then((res) => {
                            if (res.code === 200) {
                                this.$message.success('删除成功');
                            } else {
                                this.$message.error('删除失败');
                            }
                            this.getDeaprtData();
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        handleAdd() {
            this.form = new Object();
            this.addVisible = true;
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        saveEdit() {
            if (this.addVisible) {
                let params = {
                    departName: this.form.departName,
                    desc: this.form.desc
                };
                this.$refs.form.validate((vaild) => {
                    if (vaild) {
                        api.saveDepart(params)
                            .then((res) => {
                                if (res.code === 200) {
                                    this.$message.success(res.msg);
                                } else {
                                    this.$message.error(res.msg);
                                }
                                this.addVisible = false;
                                this.getDeaprtData();
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    }
                });
            }
            if (this.editVisible) {
                let params = {
                    departId: this.form.departId,
                    departName: this.form.departName,
                    desc: this.form.desc
                };
                this.$refs.form.validate((vaild) => {
                    if (vaild) {
                        api.saveDepart(params)
                            .then((res) => {
                                if (res.code === 200) {
                                    this.$message.success(res.msg);
                                } else {
                                    this.$message.error(res.msg);
                                }
                                this.editVisible = false;
                                this.getDeaprtData();
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    }
                });
            }
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
